package com.zlj.jdbc.dbutils;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import com.zlj.jdbc.jdbcUtils02.JdbcUtils;

/**
 * 测试QR Demo
 * 
 * @author bashen
 *
 */
public class QRTestDemo {
	@Test
	public void test01() throws SQLException {
		//Employee employee = new Employee(5,"marry","marry@163.com","male");
		//addEmployee(employee);
		Employee emp = queryEmployee(5);
		//Employee [id=5, name=marry, email=marry@163.com, gender=male]
		System.out.println(emp);
	}
	
	public void addEmployee(Employee employee) throws SQLException {
		//创建对象时给出连接池
		QR qr = new QR(JdbcUtils.getDataSource());
		//给出sql模板
		String sql = "insert into employee values(?,?,?,?)";
		//给出参数
		Object[] params = {employee.getId(),employee.getName(),employee.getEmail(),employee.getGender()};
		//调用update执行增、删、改
		qr.update(sql, params);
	}
	
	public Employee queryEmployee(int id) throws SQLException {
		//创建对象时给出连接池
	    QR<Employee> qr = new QR<Employee>(JdbcUtils.getDataSource());
	    String sql = "select * from employee where id = ?";
	    Object[] params = {id};
	    RsHandler<Employee> rh = new RsHandler<Employee>() {
			@Override
			public Employee handler(ResultSet rs) throws SQLException {
                Employee employee = new Employee();
                while(rs.next()) {
                	employee.setId(rs.getInt("id"));
                	employee.setName(rs.getString("name"));
                	employee.setEmail(rs.getString("email"));
                	employee.setGender(rs.getString("gender"));
                }
                return employee;
			}
		};
	    return qr.query(sql, rh, params);
	}
}
